﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using DTO;
using AutoMapper;

namespace Data
{
   public class BaoCaoTonRepository
    {
       private static BaoCaoTonDTO MapBaoCaoTonEFToBaoCaoTonDTO(BAOCAOTON baocaotonEF)
       {
           Mapper.CreateMap<BAOCAOTON, BaoCaoTonDTO>();
           return Mapper.Map<BAOCAOTON, BaoCaoTonDTO>(baocaotonEF);
       }
       private static BAOCAOTON MapBaoCaoTonDTOToBaoCaoTonEF(BaoCaoTonDTO baocaotonDTO)
       {
           Mapper.CreateMap<BaoCaoTonDTO, BAOCAOTON>();
           return Mapper.Map<BaoCaoTonDTO, BAOCAOTON>(baocaotonDTO);
       }
       public static List<BaoCaoTonDTO> GetAllBaoCaoTon()
       {
           List<BaoCaoTonDTO> list = new List<BaoCaoTonDTO>();
           using(QuanLyNhaSachEntities context=new QuanLyNhaSachEntities())
           {
               try
               {
                   var query=from baocaoton in context.BAOCAOTONList
                             select baocaoton;
                   foreach(var baocaotonEF in query)
                   {
                       BaoCaoTonDTO baocaotonDTO=MapBaoCaoTonEFToBaoCaoTonDTO(baocaotonEF);
                       list.Add(baocaotonDTO);
                   }
               }
                catch(Exception)
               {
                }
              
           }
           return list;
       }
       public void Insert(BaoCaoTonDTO baocaotonDTO)
       {
           using (QuanLyNhaSachEntities context = new QuanLyNhaSachEntities())
           {
               try
               {
                   BAOCAOTON baocaotonEF = MapBaoCaoTonDTOToBaoCaoTonEF(baocaotonDTO);
                   context.AddToBAOCAOTONList(baocaotonEF);
                   context.SaveChanges();
               }
               catch (Exception)
               {

               }
           }
       }
       public void Update(BaoCaoTonDTO baocaotonDTO)
       {
           using (QuanLyNhaSachEntities context = new QuanLyNhaSachEntities())
           {
               try
               {
                   EntityKey key = context.CreateEntityKey("BAOCAOTONList", new BAOCAOTON { MaBaoCaoTon = baocaotonDTO.MaBaoCaoTon });
                   BAOCAOTON origbaocaoton = context.GetObjectByKey(key) as BAOCAOTON;
                   context.Detach(origbaocaoton);
                   context.Attach(origbaocaoton);
                   BAOCAOTON updatebaocaoton = MapBaoCaoTonDTOToBaoCaoTonEF(baocaotonDTO);
                   context.ApplyCurrentValues<BAOCAOTON>("BAOCAOTONList", updatebaocaoton);
                   context.SaveChanges();
               }
               catch
               {
               }
           }
       }
    }
}
